var express = require('express');
var router = express.Router();
var Crypto = require("crypto-js");
/* GET home page. */
router.get('/', function(req, res, next) {
  var a = {
    title:"test"
  };
  res.json(a);
});

router.post('/', function(req, res, next) {
    console.log(req.POST)
    var iv = req.POST["iv"];
    var key = req.POST["key"];
    var data = req.POST["data"];
    iv =  Crypto.enc.Hex.parse(iv);
    var decryptedData = Crypto.AES.decrypt(data, Crypto.SHA256(key), {
                iv: iv,
                mode: Crypto.mode.CBC,
                padding: Crypto.pad.Pkcs7
            });
    var decryptedStr = decryptedData.toString(Crypto.enc.Utf8);
    var result = JSON.parse(decryptedStr);
    
    for (r in result.result) {
        var id = result.result[r].id;
        var dataEJ = {
            data : id
        };
        var encryptedData = Crypto.AES.encrypt(JSON.stringify(dataEJ), Crypto.SHA256(key), {
            iv: iv,
            mode: Crypto.mode.CBC,
            padding: Crypto.pad.Pkcs7
        });
        result.result[r].encry_data = encodeURIComponent(encryptedData.toString());
    }
    console.log(result)
    res.json(result);
});

router.post('/encry', function(req, res, next) {
    var id = req.GET['data']
    var iv = req.POST["iv"];
    var key = req.POST["key"];
    iv =  Crypto.enc.Hex.parse(iv);
    var dataEJ = {
        data : id
    };
    var encryptedData = CryptoJS.AES.encrypt(JSON.stringify(dataEJ), Crypto.SHA256(key), {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    var a = {
        data:encodeURIComponent(encodeData)
    };
    res.json(a);
});
module.exports = router;
